package com.chao.deeply.aqs;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author : Rookie
 * @description : 控制同一时间并发线程的数目。能够完成对于信号量的控制，可以控制某个资源可被同时访问的个数。
 * @date : 2023/4/27
 */
public class SemaphoreTest {

    private static int THREAD_COUNT = 2000;

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 允许3个线程同时执行
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <= THREAD_COUNT; i++) {
            int finalI = i;
            executorService.execute(() -> {
                try {
                    // 获得许可
                    semaphore.acquire();
                    test(finalI);
                    // 释放许可
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private static void test(int threadNum) throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        System.out.println("线程" + threadNum + "执行");
    }
}
